package com.ruoyi.socket.business;

import com.google.common.base.Throwables;
import com.ruoyi.socket.util.ByteBufStringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * Handles a server-side channel.
 */
@ChannelHandler.Sharable //标识可以被多个类共享
public class BusinessInboundHandler
        extends ChannelInboundHandlerAdapter { // (1) SimpleChannelInboundHandler类会默认自动释放资源
    //保留所有与服务器建立连接的channel对象
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    /**
     * chanelRead() 事件处理方法。每当从客户端收到新的数据时，这个方法会在收到消息时被调用
     * 收到的消息的类型是 ByteBuf
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        String buf = ByteBufStringUtils.convertByteBufToString(byteBuf);
        String simpleData = buf.replace("\r\n", "");
        // todo 服务层处理业务逻辑
        BusinessHandler instance = BusinessHandler.getInstance();
        String result = instance.handlerDeviceGateWay(simpleData);
        ctx.writeAndFlush(Unpooled.buffer().writeBytes(result.getBytes()));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.fireChannelActive();
        channelGroup.add(ctx.channel());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        cause.printStackTrace();
        System.out.println(" 业务层数据异常 exceptionCaught... " + Throwables.getStackTraceAsString(cause));
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
//        System.out.println("channelReadComplete...");
    }


}